<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-质检记录`"
		width="1100px"
		:show-content-loading="showLoading"
		:save-btn-loading="saveBtnLoading"
		append-to-body
		:show-confirm-btn="false"
		:show-close-btn="true"
		:show-save-btn="false"
		:show-cancel-btn="false"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-close="onVisibleChange"
		@on-visible-change="onVisibleChange"
	>
		<div ref="box1">
			<el-form ref="ruleForm" :model="ruleForm" label-width="90px" :show-message="false">
				<el-row>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
							<jk-date-picker
								v-model="ruleForm.belongDate"
								disabled
								type="date"
								size="medium"
								style="width: 100%;"
								placeholder="日期"
							></jk-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="检验类型">
							<el-select v-model="ruleForm.typeId" disabled size="medium" placeholder="检验类型" class="width-100-percent">
								<el-option
									v-for="item in examineList"
									:key="item.id"
									:value="item.id"
									:label="item.name"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="工序">
							<el-select v-model="ruleForm.processCode" disabled size="medium" placeholder="工序" class="width-100-percent">
								<el-option
									v-for="item in processList"
									:key="item.code"
									:value="item.code"
									:label="item.name"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="质检员">
							<span class="read-only-2">{{ ruleForm.empName }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="备注">
							<el-input v-model="ruleForm.remark" disabled type="textarea" :rows="1" class="width-100-percent" placeholder="请输入"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="质量情况">
							<el-input v-model="ruleForm.qualitySituation" disabled type="textarea" :rows="1" class="width-100-percent" placeholder="请输入"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<div style="display: flex" class="margin-bottom-4">
					<jk-button type="primary" size="mini" disabled>
						<span class="item-gap">{{ ruleForm.productName || '选择品种' }}</span>
						<span class="el-icon-edit"></span>
					</jk-button>
					<el-popover
						placement="right"
						width="600"
						trigger="click"
					>
						<jk-table border :data="productionList" :height="250">
							<vxe-column title="品种" align="left" field="name" :min-width="110"></vxe-column>
							<vxe-column title="批号" align="left" field="batchCode" :min-width="110"></vxe-column>
							<vxe-column title="删除操作" align="center" field="batchCode" :width="75">
								<template slot-scope="scope">
									<el-button icon="el-icon-minus" size="mini" disabled @click="removeProduct(scope.rowIndex)"></el-button>
								</template>
							</vxe-column>
							<vxe-column title="上下操作" align="center" field="batchCode" :width="120">
								<template slot-scope="scope">
									<div style="display:flex;">
										<el-button icon="el-icon-top" size="mini" disabled @click="topProduct(scope.rowIndex)"></el-button>
										<el-button icon="el-icon-bottom" size="mini" disabled @click="bottomProduct(scope.rowIndex)"></el-button>
									</div>
								</template>
							</vxe-column>
						</jk-table>
						<jk-button slot="reference" type="warning" size="mini" style="margin-left: 5px">
							<span class="item-gap">展开品种</span>
							<span class="el-icon-arrow-down"></span>
						</jk-button>
					</el-popover>
				</div>
			</el-form>
		</div>
		<jk-table v-if="ruleForm.productList.length === 0" border :height="dialogTableHeight - 20"></jk-table>
		<el-tabs v-else v-model="activeName" type="border-card">
			<el-tab-pane
				v-for="(productItem, productIndex) in ruleForm.productList || []"
				:key="productIndex"
				:label="productItem.modelName"
				:name="productItem.modelName"
			>
				<jk-table border :data="productItem.productList" :height="450">
					<vxe-column title="品种" align="left" field="productName" :min-width="110"></vxe-column>
					<vxe-column title="批号" align="left" field="batchCode" :width="120"></vxe-column>
					<vxe-column title="指标项" align="left" field="name" :width="660">
						<template slot-scope="scope">
							<el-row class="flex-start-center-wrap">
								<el-col
									v-for="item in scope.row.itemList"
									:key="item.id"
									:span="12"
									class="flex-start-center"
									style="padding: 0 10px"
								>
									<div style="width: 100%; margin-right: 30px">{{ item.name || '无' }}</div>
									<el-input v-model="item.value" size="mini" disabled />
								</el-col>
							</el-row>
						</template>
					</vxe-column>
				</jk-table>
			</el-tab-pane>
		</el-tabs>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    import { formatTime, formatDate } from '../../../utils/jk/jk-tool';
    import radioSelectDialog
        from './components/radio-select-notice-dialog.vue';
    import { spinQualityInspectionModelPage, systemBusinessDictPage } from '../../../api/quality/processQuality';
    import {
        productionPrdNoticeMachineChangeProduceBreed,
        spinQualityInspectionRecordCreate, spinQualityInspectionRecordGet,
        spinQualityInspectionRecordUpdate
    } from '../../../api/quality/qualityRecord';
    export default {
        name: 'WorkshopArea',
        components: {
            radioSelectDialog,
            checkboxMachineDialog
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                examineList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                activeName: '重量',
                productionList: [],
                ruleForm: {
                    'auditState': 0,
                    'belongDate': '',
                    'code': '',
                    'empId': 0,
                    'empName': '',
                    'productList': [],
                    'modelCode': '',
                    'modelId': 0,
                    'modelName': '',
                    'processCode': '',
                    'processId': 0,
                    'processName': '',
                    'qualitySituation': '',
                    'remark': '',
                    'typeCode': '',
                    'typeId': null,
                    'typeName': ''
                },
                // 质检模板
                InspectionModelList: [],
                detailList: []
            };
        },
        methods: {
            removeProduct(index) {
                this.productionList.splice(index, 1);
                this.ruleForm.productList.forEach(item => {
                    item.productList.splice(index, 1);
                });
            },
            topProduct(index) {
                if (index > 0) {
                    const item = this.productionList.splice(index, 1)[0];
                    this.productionList.splice(index - 1, 0, item);
                    this.ruleForm.productList.forEach(productItem => {
                        const item = productItem.productList.splice(index, 1)[0];
                        productItem.productList.splice(index - 1, 0, item);
                    });
                }
            },
            bottomProduct(index) {
                if (index < this.productionList.length - 1) {
                    const item = this.productionList.splice(index, 1)[0];
                    this.productionList.splice(index + 1, 0, item);
                    this.ruleForm.productList.forEach(productItem => {
                        const item = productItem.productList.splice(index, 1)[0];
                        productItem.productList.splice(index + 1, 0, item);
                    });
                }
            },
            // 详情
            getDetailRequest() {
                return spinQualityInspectionRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || [];
                        this.detailList = res.data.res || [];
                        this.gitRecombineDetail();
                    }
                });
            },
            // 详情再组合暂时
            gitRecombineDetail() {
                if (this.detailList.productList.length !== 0) {
                    // 初始化结果数组
                    const resultArray = [];
                    // 遍历原始数据
                    this.detailList.productList.forEach(product => {
                        // 检查是否已存在对应的modelId
                        const existingModel = resultArray.find(model => model.modelId === product.modelId);
                        if (existingModel) {
                            // 如果存在，则添加产品到现有模型
                            existingModel.productList.push({
                                productId: product.productId,
                                productCode: product.productCode,
                                productName: product.productName,
                                batchCode: product.batchCode,
                                modelId: product.modelId,
                                id: product.id,
                                modelCode: product.modelCode,
                                modelName: product.modelName,
                                itemList: product.itemList
                            });
                        } else {
                            // 如果不存在，则创建新的模型条目
                            const newModelEntry = {
                                modelId: product.modelId,
                                modelCode: product.modelCode,
                                modelName: product.modelName,
                                productList: [{
                                    productId: product.productId,
                                    productCode: product.productCode,
                                    productName: product.productName,
                                    batchCode: product.batchCode,
                                    id: product.id,
                                    modelId: product.modelId,
                                    modelCode: product.modelCode,
                                    modelName: product.modelName,
                                    itemList: product.itemList
                                }]
                            };
                            resultArray.push(newModelEntry);
                        }
                    });
                    // 品种列表
                    const Array = [];
                    resultArray.length !== 0 ? resultArray[0].productList.forEach(x => {
                        x.name = x.productName;
                    }) : [];
                    Array.push(...resultArray[0].productList);
                    this.ruleForm.productList = resultArray || [];
                    this.productionList = Array || [];
                    this.activeName = this.ruleForm.productList[0].modelName || '';
                } else {
                }
            },
            takeProductToTem() {
                const arr = JSON.parse(JSON.stringify(this.productionList));
                this.InspectionModelList.forEach(x => {
                    this.ruleForm.productList.push(
                        {
                            modelName: x.name,
                            modelId: x.id,
                            productList: arr.map(item => ({
                                productName: item.name,
                                productCode: item.code,
                                productId: item.id,
                                batchCode: item.batchCode,
                                modelName: x.name,
                                modelId: x.id,
                                modelCode: x.code,
                                itemList: JSON.parse(JSON.stringify(x.itemList)) || []
                            }))
                        }
                    );
                });
            },
            // 获取成品半成品
            getTypeListRequest() {
                const params = {
                    categoryCode: 'QUALITY_TYPE',
                    pageSize: 100,
                    pageNo: 1
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.examineList = res.data.res || [];
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                await this.getTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.custom-scroll-card {
    height: 50vh; /* 你可以根据需要设定高度 */
    overflow-y: auto; /* 启用垂直滚动条 */
}
.product-container {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    overflow: auto;
    //justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    .product-item {
        width: 200px;
        border: solid 1px #dcdee2;
        border-radius: 4px;
        margin-right: 4px;
        overflow: hidden;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.4s;
        .product-label {
            height: 34px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-bottom: solid 1px #eee;
            background: #f8f8f9;
        }
        .product-content {
            height: 60px;
            padding: 12px;
            box-sizing: border-box;
        }
    }
}

</style>
